/*
	File:  AnimatingTabView.m

	Abstract:  An NSTabView subclass that animates tab switches using Core Image "Transition" Filters or Core Graphics Transitions

	Version:  1.0

*/

#import "AnimatingTabView.h"
#import <QuartzCore/QuartzCore.h>

// Now a float set in awakeFromNib.
/*#define TRANSITION_DURATION		 1
#define TRANSITION_SLOWMO_DURATION  3.0*/

// Create a subclass of NSAnimation that we'll use to drive the transition.
@interface TabViewAnimation : NSAnimation
@end

// Convenience function to clear an NSBitmapImageRep's bits to zero.
static void ClearBitmapImageRep(NSBitmapImageRep *bitmap) {
	unsigned char *bitmapData = [bitmap bitmapData];

	if (bitmapData)
		// A fast alternative to filling with [NSColor clearColor]
		bzero(bitmapData, [bitmap bytesPerRow] * [bitmap pixelsHigh]);
}

@implementation AnimatingTabView
/* The applicationShouldTerminateAfterLastWindowClosed is just for the demo.
*	When you use this subclass, you can get rid of it
*	and delete the AnimatingTabView as the delegate of File's Owner in Interface Builder.
*/
-(BOOL)applicationShouldTerminateAfterLastWindowClosed:(id)sender{
	return 1;
}

// Initializes the attributes that AnimatingTabView adds to NSTabView.  This method is called by -initWithFrame:, and is also used by our Interface Builder palette.
// We don't use this method in the demo, as we have no need of it ;)
/*- (void)initAddedProperties {
	// Make "Cube" the default tranistion style.
	transitionStyle = CGCube;
}*/

- (void)awakeFromNib {
	NSBundle *bundle = [NSBundle bundleForClass:[self class]];

	// Preload shading bitmap to use in transitions (borrowed from the "Fun House" Core Image example).
	NSData *shadingBitmapData = [NSData dataWithContentsOfFile:[bundle pathForResource:@"restrictedshine" ofType:@"tiff"]];
	NSBitmapImageRep *shadingBitmap = [[[NSBitmapImageRep alloc] initWithData:shadingBitmapData] autorelease];
	inputShadingImage = [[CIImage alloc] initWithBitmapImageRep:shadingBitmap];

	// Preload mask bitmap to use in transitions.
	NSData *maskBitmapData = [NSData dataWithContentsOfFile:[bundle pathForResource:@"transitionmask" ofType:@"jpg"]];
	NSBitmapImageRep *maskBitmap = [[[NSBitmapImageRep alloc] initWithData:maskBitmapData] autorelease];
	inputMaskImage = [[CIImage alloc] initWithBitmapImageRep:maskBitmap];

	// init stuff
	TRANSITION_DURATION = 1;
	TRANSITION_SLOWMO_DURATION = 3;

	// transition style set here.
	transitionStyle = CGCube; [[self window] center];
}

#pragma mark -
#pragma mark *** Accessors ***

//	We don't need to use this Action method.  To make it work, we
// <control>-drag from our popup menu onto the AnimatingTabView and this
//	method would be called to switch transition styles.  But, we can do it with bindings instead.
//	We drag an NSObjectController (Green Cube) into our nib, rename it "AnimatedTabControllerAlias", and
//	<control>-drag from it to the AnimatingTabView and set the "content" connection.  Then we select the
//	"popup menu" and chose the "Bindings" panel in the Inspector.  There we set the binding of the "selectedTag"
//	field to be: "AnimatedTabControllerAlias", "selection", "transitionStyle".
//	No Code!
//  However, in this demo I'm using transitionChange: since I need to have two separate popups with only
//  half the transitions in each.

- (IBAction)transitionChange:(id)sender {
	[self setTransitionStyle:[[sender selectedItem] tag]];
}

/*  Next methods two for getting / setting transitionStlye */
- (AnimatingTabViewTransitionStyle)transitionStyle {
	return transitionStyle;
}

- (void)setTransitionStyle:(AnimatingTabViewTransitionStyle)newTransitionStyle {
	transitionStyle = newTransitionStyle;
}

#pragma mark -
#pragma mark *** NSTabView Method Overrides ***

- (void)drawRect:(NSRect)rect {
	// First, draw the normal TabView content.  If we're animating, we will have hidden the TabView's content view, so invoking [super drawRect:rect] will just draw the tabs, border, and inset background.
	[super drawRect:rect];

	// If we're in the middle of animating, composite the animation result atop the base TabView content.
	if (animation != nil) {
		// Get outputCIImage for the current phase of the animation.  (This doesn't actually cause the image to be rendered just yet.)
		[transitionFilter setValue:[NSNumber numberWithFloat:[animation currentValue]] forKey:@"inputTime"];
		CIImage *outputCIImage = [transitionFilter valueForKey:@"outputImage"];

		// Composite the outputImage into the view (which triggers on-demand rendering of the result).
		[outputCIImage drawInRect:imageRect fromRect:NSMakeRect(0, imageRect.size.height, imageRect.size.width, -imageRect.size.height) operation:NSCompositeSourceOver fraction:1.0];
	}
}

//
//	For more information regarding CI transition filters, go to "Using Core Image Filters" : "Using Transition Effects" section of the Core Image Programming Guide
//	at http://developer.apple.com/documentation/GraphicsImaging/Conceptual/CoreImaging/index.html
//
- (void)createTransitionFilterForRect:(NSRect)rect initialCIImage:(CIImage *)initialCIImage finalCIImage:(CIImage *)finalCIImage {
	CIFilter *maskScalingFilter = nil;
	CGRect maskExtent;

	switch (transitionStyle) {
		case CICopyMachine:
			transitionFilter = [[CIFilter filterWithName:@"CICopyMachineTransition"] retain];
			[transitionFilter setDefaults];
			[transitionFilter setValue:[CIVector vectorWithX:rect.origin.x Y:rect.origin.y Z:rect.size.width W:rect.size.height] forKey:@"inputExtent"];
			break;

		case CIDisintegrate:
			transitionFilter = [[CIFilter filterWithName:@"CIDisintegrateWithMaskTransition"] retain];
			[transitionFilter setDefaults];

			// Scale our mask image to match the transition area size, and set the scaled result as the "inputMaskImage" to the transitionFilter.
			maskScalingFilter = [CIFilter filterWithName:@"CILanczosScaleTransform"];
			[maskScalingFilter setDefaults];
			maskExtent = [inputMaskImage extent];
			float xScale = rect.size.width / maskExtent.size.width;
			float yScale = rect.size.height / maskExtent.size.height;
			[maskScalingFilter setValue:[NSNumber numberWithFloat:yScale] forKey:@"inputScale"];
			[maskScalingFilter setValue:[NSNumber numberWithFloat:xScale / yScale] forKey:@"inputAspectRatio"];
			[maskScalingFilter setValue:inputMaskImage forKey:@"inputImage"];

			[transitionFilter setValue:[maskScalingFilter valueForKey:@"outputImage"] forKey:@"inputMaskImage"];
			break;

		case CIDissolve:
			transitionFilter = [[CIFilter filterWithName:@"CIDissolveTransition"] retain];
			[transitionFilter setDefaults];
			break;

		case CIFlash:
			transitionFilter = [[CIFilter filterWithName:@"CIFlashTransition"] retain];
			[transitionFilter setDefaults];
			[transitionFilter setValue:[CIVector vectorWithX:NSMidX(rect) Y:NSMidY(rect)] forKey:@"inputCenter"];
			[transitionFilter setValue:[CIVector vectorWithX:rect.origin.x Y:rect.origin.y Z:rect.size.width W:rect.size.height] forKey:@"inputExtent"];
			break;

		case CIMod:
			transitionFilter = [[CIFilter filterWithName:@"CIModTransition"] retain];
			[transitionFilter setDefaults];
			[transitionFilter setValue:[CIVector vectorWithX:NSMidX(rect) Y:NSMidY(rect)] forKey:@"inputCenter"];
			break;

		case CIPageCurl:
			transitionFilter = [[CIFilter filterWithName:@"CIPageCurlTransition"] retain];
			[transitionFilter setDefaults];
			[transitionFilter setValue:[NSNumber numberWithFloat:-M_PI_4] forKey:@"inputAngle"];
			[transitionFilter setValue:initialCIImage forKey:@"inputBacksideImage"];
			[transitionFilter setValue:inputShadingImage forKey:@"inputShadingImage"];
			[transitionFilter setValue:[CIVector vectorWithX:rect.origin.x Y:rect.origin.y Z:rect.size.width W:rect.size.height] forKey:@"inputExtent"];
			break;

		case CISwipe:
			transitionFilter = [[CIFilter filterWithName:@"CISwipeTransition"] retain];
			[transitionFilter setDefaults];
			break;

		case CIRipple:
		default:
			transitionFilter = [[CIFilter filterWithName:@"CIRippleTransition"] retain];
			[transitionFilter setDefaults];
			[transitionFilter setValue:[CIVector vectorWithX:NSMidX(rect) Y:NSMidY(rect)] forKey:@"inputCenter"];
			[transitionFilter setValue:[CIVector vectorWithX:rect.origin.x Y:rect.origin.y Z:rect.size.width W:rect.size.height] forKey:@"inputExtent"];
			[transitionFilter setValue:inputShadingImage forKey:@"inputShadingImage"];
			break;
	}
	[transitionFilter setValue:initialCIImage forKey:@"inputImage"];
	[transitionFilter setValue:finalCIImage forKey:@"inputTargetImage"];
}

- (void)selectTabViewItem:(NSTabViewItem *)tabViewItem {
	if (!transitionStyle) // no transition style
		[super selectTabViewItem:tabViewItem];
	else if(transitionStyle < 9) { // Otherwise is the transition for CoreGraphics
		int option, toTab;

		int lastTab = [self numberOfTabViewItems] - 1;
		// fromTab set before changing the tab, as we need to know where we're coming from
		int fromTab = [self indexOfTabViewItem:[self selectedTabViewItem]];
		// Change the tab. wont be rendered yet.
		[super selectTabViewItem:tabViewItem];
		// now we can set toTab.
		toTab = [self indexOfTabViewItem:[self selectedTabViewItem]];

		// Following logic for making different directions: the directions follow a cube style pattern and make it look more realistic
		if (toTab > fromTab) { // moving up
			if (toTab == lastTab || !fromTab) // to last tab or from first tab
				option = CGSUp;
			else
				option = CGSLeft;
		} else if (toTab < fromTab) { // moving back
			if (!toTab || fromTab == lastTab) // to first tab or from last tab
				option = CGSDown;
			else
				option = CGSRight;
		}

		// Runs the CoreGraphics animation
		[self turnWithTransition:transitionStyle option:option duration:(slowMotionDemo ? TRANSITION_SLOWMO_DURATION : TRANSITION_DURATION)];
		// if we were slowmo, we don't want it on by default next time.
		slowMotionDemo = 0;
	} else {
		// It's coreImage

		// Make a note of the content view of the NSTabViewItem we're switching from, and the content view of the one we're switching to.
		NSView *initialContentView = [[self selectedTabViewItem] view];
		NSView *finalContentView = [tabViewItem view];

		// Compute bounds and frame rectangles big enough to encompass both views.  (We'll use imageRect later, to composite the animation frames into the right place within the AnimatingTabView.)
		NSRect rect = NSUnionRect([initialContentView bounds], [finalContentView bounds]);
		imageRect = NSUnionRect([initialContentView frame], [finalContentView frame]);

		// Render the initialContentView to a bitmap.  When using the -cacheDisplayInRect:toBitmapImageRep: and -displayRectIgnoringOpacity:inContext: methods, remember to first initialize the destination to clear if the content to be drawn won't cover it with full opacity.
		NSBitmapImageRep *initialContentBitmap;
		if (transitionStyle == CIPageCurl) {
			// For the "Page Curl" transition style, we want the initialContentBitmap to include the opaque window background, so we use the time-honored -initWithFocusedViewRect: approach to capturing a snapshot of the view content.
			[self lockFocus];
			initialContentBitmap = [[[NSBitmapImageRep alloc] initWithFocusedViewRect:imageRect] autorelease];
			[self unlockFocus];
		} else {
			initialContentBitmap = [initialContentView bitmapImageRepForCachingDisplayInRect:rect];
			ClearBitmapImageRep(initialContentBitmap);
			[initialContentView cacheDisplayInRect:rect toBitmapImageRep:initialContentBitmap];
		}

		// Invoke super's implementation of -selectTabViewItem: to switch to the requested tabViewItem.  The NSTabView will mark itself as needing display, but the window will not have redrawn yet, so this is our chance to animate the transition!
		[super selectTabViewItem:tabViewItem];

		// Render the finalContentView to a bitmap.
		NSBitmapImageRep *finalContentBitmap = [finalContentView bitmapImageRepForCachingDisplayInRect:rect];
		ClearBitmapImageRep(finalContentBitmap);
		[finalContentView cacheDisplayInRect:rect toBitmapImageRep:finalContentBitmap];

		// Build a Core Image filter that will morph the initialContentBitmap into the finalContentBitmap.
		CIImage *initialCIImage = [[CIImage alloc] initWithBitmapImageRep:initialContentBitmap];
		CIImage *finalCIImage = [[CIImage alloc] initWithBitmapImageRep:finalContentBitmap];
		[self createTransitionFilterForRect:rect initialCIImage:initialCIImage finalCIImage:finalCIImage];
		[initialCIImage release];
		[finalCIImage release];

		// Create an instance of TabViewAnimation to drive the transition over time.  Set the AnimatingTabView to be the TabViewAnimation's delegate, so the TabViewAnimation will know which view to redisplay as the animation progresses.
		animation = [[TabViewAnimation alloc] initWithDuration:(slowMotionDemo ? TRANSITION_SLOWMO_DURATION : TRANSITION_DURATION) animationCurve:NSAnimationEaseInOut];
		[animation setDelegate:self];

		// Hide the TabView's new content view for the duration of the animation.
		[finalContentView setHidden:1];

		// Run the animation synchronously.
		[animation startAnimation];

		// Clean up after the animation has finished.
		[animation release];
		animation = 0;
		[transitionFilter release];
		transitionFilter = 0;
		slowMotionDemo = 0;
		[finalContentView setHidden:0];
		[self setNeedsDisplay:1];
	}
}

#pragma mark -
#pragma mark *** Mouse Event Handling ***

// This override exists only as a means to enable slow-motion "demo" mode.
// It simply makes a note of whether the [Shift] key was pressed when the mouse was last clicked in the TabView.
// Needs to have the tabs showing, but we don't in the demo.
- (void)mouseDown:(NSEvent *)theEvent {
	if ([theEvent modifierFlags] & NSShiftKeyMask)
		slowMotionDemo = 1;
	[super mouseDown:theEvent];
}

#pragma mark -
#pragma mark *** Core Graphics ***

// CoreGraphics transition
-(void)turnWithTransition:(CGSTransitionType)transition option:(CGSTransitionOption)option duration:(float)duration {
	// declare our variables
	CGSTransitionSpec spec; int handle = -1;

	// specify our specifications
	spec.unknown1 = 0;
	spec.type = transition; // cube swap etc
	spec.option = option | (1 << 7); //  transparent mask
	spec.backColour = 0; // doesn't matter anyway since we're transparent
	spec.wid = [[self window] windowNumber]; // windowNumber: 0 for whole desktop ;)

	// Let's get a connection
	CGSConnection cgs = _CGSDefaultConnection();

	// Create a transition
	CGSNewTransition(cgs, &spec, &handle);

	// Redraw the window - !important otherwise you get the tab changing only after the transition
	[[self window] display];

	// Pass the connection handle and duration to apply the animation
	CGSInvokeTransition(cgs, handle, duration);
	// We need to wait for the transition to finish before we get rid of it, otherwise we'll get all sorts of nasty errors... or maybe not
	usleep((useconds_t)(duration*1000000));

	// Finally release all our variables
	CGSReleaseTransition(cgs, handle); handle = 0;
}

@end

@implementation TabViewAnimation
// Override NSAnimation's -setCurrentProgress: method, and use it as our point to hook in and advance our Core Image transition effect to the next time slice.
- (void)setCurrentProgress:(NSAnimationProgress)progress {
	// First, invoke super's implementation, so that the NSAnimation will remember the proposed progress value and hand it back to us when we ask for it in AnimatingTabView's -drawRect: method.
	[super setCurrentProgress:progress];

	// Now ask the AnimatingTabView (which set itself as our delegate) to display.  Sending a -display message differs from sending -setNeedsDisplay: or -setNeedsDisplayInRect: in that it demands an immediate, synchronous redraw of the view.  Most of the time, it's preferable to send a -setNeedsDisplay... message, which gives AppKit the opportunity to coalesce potentially numerous display requests and update the window efficiently when it's convenient.  But for a synchronously executing animation, it's appropriate to use -display.
	[[self delegate] display];
}
@end